#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
共享充电宝数据仓库 - 服务启动脚本
"""

import os
import sys
import subprocess
import webbrowser
import threading
import time

def check_dependencies():
    """检查依赖包是否安装"""
    required_packages = ['flask', 'flask-cors', 'pandas']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print("❌ 缺少以下依赖包:")
        for package in missing_packages:
            print(f"   - {package}")
        print("\n📦 请运行以下命令安装依赖:")
        print(f"   pip install {' '.join(missing_packages)}")
        return False
    
    return True

def check_data_files():
    """检查数据文件是否存在"""
    data_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data', 'ADS')
    required_files = [
        'brand_revenue_summary.csv',
        'user_behavior_summary.csv',
        'time_summary.csv',
        'region_usage_summary.csv',
        'region_heatmap_data.csv'
    ]
    
    missing_files = []
    for file in required_files:
        file_path = os.path.join(data_path, file)
        if not os.path.exists(file_path):
            missing_files.append(file)
    
    if missing_files:
        print("❌ 缺少以下数据文件:")
        for file in missing_files:
            print(f"   - {file}")
        print(f"\n📁 请确保数据文件存在于: {data_path}")
        return False
    
    return True

def open_browser():
    """延迟打开浏览器"""
    time.sleep(2)  # 等待服务器启动
    frontend_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'frontend', 'index.html')
    frontend_url = f"file:///{frontend_path.replace(os.sep, '/')}"

    print(f"🌐 正在打开前端页面: {frontend_url}")
    try:
        webbrowser.open(frontend_url)
        print("✅ 前端页面已在浏览器中打开!")
    except Exception as e:
        print(f"⚠️  无法自动打开浏览器: {str(e)}")
        print(f"📋 请手动打开: {frontend_path}")

def main():
    """主函数"""
    print("🔍 检查运行环境...")

    # 检查依赖
    if not check_dependencies():
        sys.exit(1)

    # 检查数据文件
    if not check_data_files():
        sys.exit(1)

    print("✅ 环境检查通过!")
    print("🚀 启动API服务...")

    # 启动Flask应用
    try:
        from app import app

        # 在后台线程中延迟打开浏览器
        browser_thread = threading.Thread(target=open_browser)
        browser_thread.daemon = True
        browser_thread.start()

        print("📡 API服务运行在: http://localhost:5000")
        print("🎯 前端页面将自动打开...")
        print("⏹️  按 Ctrl+C 停止服务")

        app.run(debug=False, host='0.0.0.0', port=5000, use_reloader=False)
    except KeyboardInterrupt:
        print("\n👋 服务已停止")
    except Exception as e:
        print(f"❌ 启动失败: {str(e)}")
        sys.exit(1)

if __name__ == '__main__':
    main()
